package com.yiyw.herostory.server;

import com.yiyw.herostory.factory.CmdHandlerFactory;
import com.yiyw.herostory.factory.GameMsgProtocolFactory;
import com.yiyw.herostory.pipeline.Inbound.GameMasHandler;
import com.yiyw.herostory.pipeline.Inbound.GameMsgDecoder;
import com.yiyw.herostory.pipeline.outBound.GameMsgEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * @Author yiyw
 * @Description Netty 服务端
 * @Date 2022/8/18 22:00
 **/
@Slf4j
@Component
public final class NettyServer {
    /**
     * 主线程处理器
     */
    private EventLoopGroup boosGroup;
    /**
     * 任务处理器
     */
    private EventLoopGroup workGroup;
    /**
     * 服务启动助手
     */
    ServerBootstrap bootstrap;
    /**
     * 信道
     */
    Channel channel;

    /**
     * @description: 〈Netty 启动器〉
     * @param port  Netty 启动端口
     * @return: io.netty.channel.ChannelFuture
     * @author 一夏
     * @date: 2022/8/18 22:54
     */
    public ChannelFuture nettyStart(int port) {
        // 初始化数据
        CmdHandlerFactory.init();
        GameMsgProtocolFactory.init();
        boosGroup = new NioEventLoopGroup();
        workGroup = new NioEventLoopGroup();

        bootstrap = new ServerBootstrap();
        bootstrap.group(boosGroup, workGroup)
                // 设置服务器通道为 ServerSocketChannel
                .channel(NioServerSocketChannel.class)
                // 设置 BossGroup 连接队列的大小
                .option(ChannelOption.SO_BACKLOG, 128)
                // 设置 workerGroup 线程保持活动的连接状态
                .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                // 为 workerGroup 创建一个通道初始化对象，给我们的 workerGroup 的 EventLoop 对应的管道设置处理器
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 添加自定义处理器
                        socketChannel.pipeline().addLast(new HttpServerCodec())  // 添加 HTTP 编解码器
                                .addLast(new HttpObjectAggregator(65535)) // 内容长度限制
                                .addLast(new WebSocketServerProtocolHandler("/websocket")) // WebSocket 协议处理器, 在这里处理握手、ping、pong 等消息
                                .addLast(new GameMsgDecoder())
                                .addLast(new GameMsgEncoder())
                                .addLast(new GameMasHandler());
                    }
                });

        try {
            // 绑定端口
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            if (channelFuture.isSuccess()) {
                log.info("server start success.");
            }
            channel = channelFuture.channel();
            return channelFuture;
        } catch (InterruptedException e) {
            log.error("system run time has error: {}", e.getMessage(), e);
            return null;
        }
    }


    /**
     * @description: 〈 Netty 销毁事件 〉
     * @param
     * @return: void
     * @author 一夏
     * @date: 2022/8/18 22:55
     */
    public void destroy() {
        log.info("netty server will destroy...");
        if (channel != null) {
            channel.close();
        }
        if (boosGroup != null) {
            boosGroup.shutdownGracefully();
        }
        if (workGroup != null) {
            workGroup.shutdownGracefully();
        }
    }
}
